﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Admin.NET.Application;

/// <summary>
/// 工艺路线服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class RoutingService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Routing> _routingRep;
    private readonly SysFileService _sysFileService;
    private readonly ISqlSugarClient _sqlSugarClient;
    private readonly SysDictTypeService _sysDictTypeService;

    public RoutingService(SqlSugarRepository<Routing> routingRep, SysFileService sysFileService, ISqlSugarClient sqlSugarClient, SysDictTypeService sysDictTypeService)
    {
        _routingRep = routingRep;
        _sysFileService = sysFileService;
        _sqlSugarClient = sqlSugarClient;
        _sysDictTypeService = sysDictTypeService;
    }

    /// <summary>
    /// 分页查询工艺路线 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询工艺路线")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<RoutingOutput>> Page(PageRoutingInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _routingRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.routingname.Contains(input.Keyword) || u.preview.Contains(input.Keyword) || u.routingtype.Contains(input.Keyword) || u.description.Contains(input.Keyword) || u.operationinstruction.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.routingname), u => u.routingname.Contains(input.routingname.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.preview), u => u.preview.Contains(input.preview.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.routingtype), u => u.routingtype.Contains(input.routingtype.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.description), u => u.description.Contains(input.description.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.operationinstruction), u => u.operationinstruction.Contains(input.operationinstruction.Trim()))
            .Select((u) => new RoutingOutput
            {
                Id = u.Id,
                routingname = u.routingname,
                preview = u.preview,
                routingtype = u.routingtype,
                routingstate = u.routingstate,
                description = u.description,
                operationinstruction = u.operationinstruction,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取工艺路线详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取工艺路线详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Routing> Detail([FromQuery] QueryByIdRoutingInput input)
    {
        return await _routingRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加工艺路线 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加工艺路线")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddRoutingInput input)
    {
        var entity = input.Adapt<Routing>();
        return await _routingRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新工艺路线 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新工艺路线")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateRoutingInput input)
    {
        var entity = input.Adapt<Routing>();
        await _routingRep.AsUpdateable(entity)
        .IgnoreColumns(u => new {
            u.preview,
            u.routingstate,
        })
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除工艺路线 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除工艺路线")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteRoutingInput input)
    {
        var entity = await _routingRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _routingRep.FakeDeleteAsync(entity);   //假删除
        //await _routingRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除工艺路线 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除工艺路线")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteRoutingInput> input)
    {
        var exp = Expressionable.Create<Routing>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _routingRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _routingRep.FakeDeleteAsync(list);   //假删除
        //return await _routingRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 上传作业指导书 ⬆️
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    [DisplayName("上传作业指导书")]
    [ApiDescriptionSettings(Name = "Uploadoperationinstruction"), HttpPost]
    public async Task<SysFile> Uploadoperationinstruction([Required] IFormFile file)
    {
        return await _sysFileService.UploadFile(new UploadFileInput { File = file, SavePath = "upload/Routing/operationinstruction" }); 
    }
    
    /// <summary>
    /// 导出工艺路线记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出工艺路线记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageRoutingInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportRoutingOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        var routingtypeDictMap = _sysDictTypeService.GetDataList(new GetDataDictTypeInput { Code = "routing _state_dictionary" }).Result.ToDictionary(x => x.Value, x => x.Label);
        list.ForEach(e => {
            e.routingtypeDictLabel = routingtypeDictMap.GetValueOrDefault(e.routingtype ?? "", e.routingtype);
        });
        return ExcelHelper.ExportTemplate(list, "工艺路线导出记录");
    }
    
    /// <summary>
    /// 下载工艺路线数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载工艺路线数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportRoutingOutput>(), "工艺路线导入模板");
    }
    
    /// <summary>
    /// 导入工艺路线记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入工艺路线记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var routingtypeDictMap = _sysDictTypeService.GetDataList(new GetDataDictTypeInput { Code = "routing _state_dictionary" }).Result.ToDictionary(x => x.Label!, x => x.Value);
            var stream = ExcelHelper.ImportData<ImportRoutingInput, Routing>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    
                    // 映射字典值
                    foreach(var item in pageItems) {
                        if (string.IsNullOrWhiteSpace(item.routingtypeDictLabel)) continue;
                        item.routingtype = routingtypeDictMap.GetValueOrDefault(item.routingtypeDictLabel);
                        if (item.routingtype == null) item.Error = "类型字典映射失败";
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.routingstate == null){
                            x.Error = "状态不能为空";
                            return false;
                        }
                        return true;
                    }).Adapt<List<Routing>>();
                    
                    var storageable = _routingRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.routingname?.Length > 32, "名称长度不能超过32个字符")
                        .SplitError(it => it.Item.preview?.Length > 32, "预览图长度不能超过32个字符")
                        .SplitError(it => it.Item.routingtype?.Length > 32, "类型长度不能超过32个字符")
                        .SplitError(it => it.Item.description?.Length > 32, "描述长度不能超过32个字符")
                        .SplitError(it => it.Item.operationinstruction?.Length > 32, "作业指导书长度不能超过32个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
